package com.young.common.config;

import com.young.common.filter.CrossDomainFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * 跨域过滤器配置
 * 当web应用时,且young.filter.crossDomainFilter.enabled=true时启用
 * @author yangwei
 * @description
 * @create 2018/10/10 0010
 */
@Configuration
@ConditionalOnWebApplication
@ConditionalOnProperty(
        name = "young.filter.cross-domain-filter.enabled",
        havingValue = "true"
)
@ConfigurationProperties(prefix="young.filter.cross-domain-filter")
public class CrossDomainFilterConfiguration {

    /**
     * url匹配模式
     */
    private String urlPatterns;
    /**
     * 顺序
     */
    private Integer order;

    @Bean
    public FilterRegistrationBean crossDomainFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //创建过滤器
        CrossDomainFilter crossDomainFilter = new CrossDomainFilter();
        registrationBean.setFilter(crossDomainFilter);
        //过滤器初始化参数
        Map<String, String> initParam = new HashMap<String, String>();
        registrationBean.setInitParameters(initParam);
        //匹配url
        List<String> urlPatterns = new ArrayList<String>();
        if (this.urlPatterns != null && !"".equals(this.urlPatterns)) {
            String[] urlPatternArr = this.urlPatterns.split(",");
            if (urlPatternArr != null && urlPatternArr.length > 0){
                urlPatterns.addAll(Arrays.asList(urlPatternArr));
            }
        } else {
            urlPatterns.add("/*");
        }
        registrationBean.setUrlPatterns(urlPatterns);
        //设置顺序
        if (this.order != null) {
            registrationBean.setOrder(this.order);
        } else {
            registrationBean.setOrder(1);
        }
        return registrationBean;
    }

    public String getUrlPatterns() {
        return urlPatterns;
    }

    public void setUrlPatterns(String urlPatterns) {
        this.urlPatterns = urlPatterns;
    }

    public Integer getOrder() {
        return order;
    }

    public void setOrder(Integer order) {
        this.order = order;
    }
}
